import { SET_MESSAGE } from "@/store/action.types";
import store from "../store/index";
import { local } from "./storage";

interface Config {
  url: string;
  prot: number;
  protocol: string;
  time: number;
}

export default class WS {
  private _url: string;
  private _prot: number;
  private _protocol: string;
  private _time: number;
  private _ws!: WebSocket;
  private _timer!: number;
  constructor(config?: Config) {
    this._url = config?.url || "vue.zhufengpeixun.cn";
    this._prot = config?.prot || 80;
    this._protocol = config?.protocol || "ws";
    this._time = config?.time || 1000 * 30;
  }

  create() {
    this._ws = new WebSocket(`${this._protocol}://${this._url}:${this._prot}`);
    this._ws.onopen = this.onOpen;
    this._ws.onmessage = this.onMessage;
    this._ws.onerror = this.onError;
    this._ws.onclose = this.onClose;
  }
  send(message: string) {
    this._ws.send(message);
  }
  checkServer() {
    clearTimeout(this._timer);
    this._timer = setTimeout(() => {
      this.onClose();
      this.onError();
    }, this._time + 1000);
  }
  onOpen() {
    this._ws.send(
      JSON.stringify({
        type: "auth",
        data: local.get("token")
      })
    );
  }
  onMessage(error: any) {
    const { type, data } = JSON.parse(error.data);
    switch (type) {
      case "noAuth":
        console.log("没有权限");
        break;
      case "heartCheck":
        this.checkServer();
        this._ws.send(
          JSON.stringify({
            type: "heartCheck"
          })
        );
        break;
      default:
        store.commit(SET_MESSAGE, data);
        break;
    }
  }
  onError() {
    setTimeout(() => {
      this.create(); // 重新调用create方法 连线的
    }, 1000);
  }
  onClose() {
    this._ws.close();
  }
}
